// pages/index/share/index.js
const $api = require('../../../../request/api').API;
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import * as Storage from '../../../../utils/storage';
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    beeperId: '', //邀请方
    beeperList: [],
    chatBeeperId: '', //被邀请方
    chatName: '', //被邀请方名称
    beeperIndex: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({ beeperId, startTime }) {
    if (beeperId) {
      startTime = new Date(startTime);
      let endTime = new Date(); // 结束时间
      console.log('开始时间', startTime);
      console.log('结束时间', endTime);
      let interval = Math.floor((endTime - startTime) / 1000 / 60); // 间隔【分钟】
      console.log('分享页间隔', interval);
      // 大于十分钟失效
      if (interval > 10) {
        Toast.fail('当前分享连接已失效');
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/equipment/index'
          });
        }, 3000);
        return;
      }
      this.setData({
        beeperId
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getBeeberList();
  },
  // 点击接受邀请
  async shareLocale() {
    if (this.data.beeperList.length == 0) {
      return false;
    }
    Toast.loading('加载中');
    let res = await $api.addMicroChatFriend({
      chatBeeperId: this.data.chatBeeperId,
      chatName: this.data.chatName,
      beeperId: this.data.beeperId
    });
    if (res.data.status == 0) {
      Toast('绑定成功');
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/equipment/index'
        });
      }, 1000);
    } else {
      wx.showToast({
        title: res.data.msg,
        icon: 'error'
      });
    }
  },

  async getBeeberList() {
    let res = await $api.getAssignBeeper({
      openId: wx.getStorageSync(Storage.USER_OPEN_ID)
    });
    if (res.data.data) {
      let filteredArray = res.data.data.filter(item => item !== null);
      this.setData({
        beeperList: filteredArray
      });
      if (filteredArray.length == 1) {
        this.setData({
          beeperIndex: 0,
          chatBeeperId: filteredArray[0].id,
          chatName: filteredArray[0].name
        });
      }
    }
  },

  selectBeeper(e) {
    const index = e.detail.value;
    let beeperList = this.data.beeperList;
    this.setData({
      beeperIndex: index,
      chatBeeperId: beeperList[index].id,
      chatName: beeperList[index].name
    });
  }
});
